import csv
import json


def readCsv(path):
    infoList = []
    with open(path, 'r') as file:
        data = csv.reader(file)
        for row in data:
            infoList.append(row)
    return infoList


def writeCsv(path, data):
    with open(path, 'a', newline='') as file:
        writer = csv.writer(file)
        for row in data:
            print("rowData =", row)
            writer.writerow(row)


def writeFile(path, data):
    file = open(path, 'a')
    for row in data:
        file.write(str(row))
        file.write('\n')


def readJson(path):
    with open(path, 'r', encoding="utf-8") as file:
        data = json.load(file)
        # j = json.dumps(data, ensure_ascii=False)
        # print(j)
        print(data)


def readJson2(path, data):
    with open(path, 'a') as file:
        json.dump(data, file)


def serialize(stu):
    d = json.dumps(stu, default=serializeToDict)
    print(d)


def serialize2(jsonStr):
    j = json.loads(jsonStr, object_hook=serializeToObj)
    print(j)


def serializeToDict(dict):
    return {
        'name': dict.name,
        'age': dict.age,
        'score': dict.score
    }


def serializeToObj(d):
    return Student(d['name'], d['age'], d['score'])


path = r"../resource/image/input/test.csv"
path2 = r"../image/input/test.json"


# print(readCsv(path))
# writeCsv(path, [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# writeFile(path, "世界")
# readJson(path2)
# readJson2(path2, {"name": "mlf", "age": 22})


class Student(object):
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score


stu = Student('Bob', 20, 88)
jsonStr = '{"age": 20, "score": 88, "name": "Bob"}'

# serialize(stu)
serialize2(jsonStr)
